import os.path
import time
import traceback

import fire

FILE_CHUCK_SIZE_MB = 1
FILE_CHUCK_TIME_MS = 10


def create_file(file_dir, file_name, file_size_mb):
    file_path = os.path.join(file_dir, file_name)
    print("开始创建文件{}".format(file_path))
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    with open(file_path, "wb") as fh:
        write_size_mb = 0
        write_data = os.urandom(FILE_CHUCK_SIZE_MB * 1024 * 1024)
        while write_size_mb < file_size_mb:
            fh.write(write_data)
            fh.flush()
            os.fsync(fh.fileno())
            write_size_mb += FILE_CHUCK_SIZE_MB
            write_msg = "已写入{}MB数据，进度{:.2f}%".format(
                int(write_size_mb), round(write_size_mb * 100 / file_size_mb, 2)
            )
            print(write_msg)
            time.sleep(FILE_CHUCK_TIME_MS / 1000)
        print("完成创建文件{}".format(file_path))
    pass


def fill_disk(file_dir=".", file_count=1, file_size_mb=1):
    """
    欢迎使用磁盘填充工具。
    :param file_dir: 要填充的文件目录
    :param file_count: 要填充的文件数量
    :param file_size_mb: 要填充的文件大小(单位MB)
    """
    try:
        for file_index in range(0, file_count):
            file_name = "data_{}.bin".format(str(file_index).zfill(5))
            create_file(file_dir=file_dir, file_name=file_name, file_size_mb=file_size_mb)
    except Exception as ex:
        print("执行出错,\n异常为:{},\n堆栈为:{}".format(str(ex), traceback.format_exc()))
    pass


if __name__ == '__main__':
    fire.Fire(fill_disk)
